﻿using AutoMapper;
using B.MES.Customer.Domain;
using B.MES.Customer.Domain.DTO;
using B.MES.Customer.Infrastructure.IRepository;
using K4os.Hash.xxHash;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B.MES.Customer.Infrastructure.Repository
{
    /// <summary>
    /// 销售仓储实现层
    /// </summary>
    public class SalesManagementRepository : BaseRepository<SalesManagement>, ISalesManagementRepository
    {
        private readonly ISqlSugarClient _db;
        private readonly IMapper _mapper;
        public SalesManagementRepository(ISqlSugarClient db,IMapper mapper) : base(db)
        {
            _db = db;
            _mapper = mapper;
        }
        /// <summary>
        /// 销售添加
        /// </summary>
        /// <param name="sales"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public APIResult<SaleDto> AddSale(SaleDto sales)
        {
           
            APIResult<SaleDto> apiResult = new APIResult<SaleDto>();

            try
            {
                // 映射 SaleDto 对象为 SalesManagement 对象
                var salesManagement = _mapper.Map<SalesManagement>(sales);

                // 插入 SalesManagement 对象并获取返回的自增主键值
                var insertedSalesId = _db.Insertable(salesManagement).ExecuteReturnIdentity();

                // 准备 Sale_ProductDTO 数据并逐个插入
                foreach (var item in sales.sale_ProductDTO)
                {
                    sale_Product saleProductDTO = new sale_Product
                    {
                        Product_Id=item.Product_Id, 
                        Product_Expiry_Date = item.Product_Expiry_Date,
                        Unit_Price = item.Unit_Price,
                        Remarks = item.Remarks
                        
                    };

                    // 插入 Sale_ProductDTO 对象
                    var productInsertResult = _db.Insertable(saleProductDTO).ExecuteCommand();
                    if (productInsertResult <= 0)
                    {
                        apiResult.Code = 500; // 或其他错误码
                        apiResult.Message = "添加商品信息失败";
                        return apiResult;
                    }
                }

                apiResult.Success();
            }
            catch (Exception ex)
            {
                apiResult.Code = 500;
                apiResult.Message = "添加销售记录发生错误：" + ex.Message;
                // 在实际项目中，最好将异常信息记录到日志中
            }

            return apiResult;
        }
        /// <summary>
        /// 销售单个删除
        /// </summary>
        /// <param name="SaleId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public APIResult<SalesManagement> DeleteSale(int SaleId)
        {
            APIResult<SalesManagement> aPIResult = new APIResult<SalesManagement>();
            _db.Deleteable<SalesManagement>(SaleId).ExecuteCommand();
            aPIResult.SuccessDel();
            return aPIResult;
        }

        public APIResult<List<SalesManagement>> DeletesSale(List<SalesManagement> list)
        {
            APIResult<List<SalesManagement>> aPIResult = new APIResult<List<SalesManagement>>();
            foreach (SalesManagement item in list)
            {
                item.IsDelete = true;
            }
            _db.Updateable(list).ExecuteCommand();
            aPIResult.SuccessDel();
            return aPIResult;
        }

        /// <summary>
        /// 销售批量删除
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Client> GetClients()
        {
            return _db.Queryable<Client>().ToList();
        }
        /// <summary>
        /// 根据Id去查找销售的信息
        /// </summary>
        /// <param name="SaleId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public SalesManagement GetSaleInfo(int SaleId)
        {
            var result = _db.Queryable<SalesManagement>().InSingle(SaleId);

            return result;
        }



        /// <summary>
        /// 获取销售信息
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public PageApiResut<SaleDto> GetSalesManagement(int PageIndex, int PageSize, string? LinkMan, int? ClientId)
        {
            PageApiResut<SaleDto> pageApiResut = new PageApiResut<SaleDto>();
            var query = _db.Queryable<SalesManagement, Client>((A, B) => new JoinQueryInfos(
                JoinType.Inner, A.ClientId == B.ClientId
            )).
            Select((A, B) => new SaleDto
            {
                ClientId = A.ClientId,
                ClientName = B.ClientName,
                ContactInformation = A.ContactInformation,
                ContactNumber = A.ContactNumber,
                DestinationOfDelivery = A.DestinationOfDelivery,
                LinkMan = A.LinkMan,
                Remark = A.Remark,
                SaleId = A.SaleId,
                SalesDate = A.SalesDate,
                SalesOrderNumber = A.SalesOrderNumber,
            });

            int totalCount = query.Count();

            var list = query
                .WhereIF(!string.IsNullOrEmpty(LinkMan), A => A.LinkMan.Contains(LinkMan))
                .WhereIF(ClientId > 0, A => A.ClientId == ClientId).Where(A => A.IsDelete == false).ToPageList(PageIndex, PageSize)
                .ToList();
            //if (!string.IsNullOrEmpty(LinkMan))
            //{
            //    list=list.WhereIF(x=>x.LinkMan.Contains(LinkMan));
            //}
            //if (ClientId != 0)
            //{
            //    list=list.WhereIF(x=>x.ClientId== ClientId);
            //}
            pageApiResut.TotalCount = totalCount;
            //list = list.Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList();
            pageApiResut.Data = list;
            return pageApiResut;
        }
        /// <summary>
        /// 销售修改
        /// </summary>
        /// <param name="sales"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public int UpdateSale(SalesManagement sales)
        {
            return _db.Updateable(sales).ExecuteCommand();
        }

        /// <summary>
        /// 销售统计
        /// </summary>
        /// <returns></returns>
        public List<SalesManagementDTO> CountSale()
        {
            try
            {
                // 从数据库获取数据
                var salesData = _db.Queryable<SalesManagement>()
                                   .ToList();  // 先将数据加载到内存中

                // 在内存中处理数据
                var result = salesData
                            .GroupBy(x => x.SalesDate.ToString("yyyy-MM"))
                            .Select(t => new SalesManagementDTO
                            {
                                SlaesDate = t.Key, // 使用分组的键作为日期字符串
                                SlaesCount = t.Count()
                            })
                            .ToList();

                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }
    }
}
